<template>
  <div class="request-party-service-manage">
    <div class="app-container">
      <div class="mainbox">
        <Header :header-name="$route.meta.title" />

        <div class="request-party-service-manage-body">
          <!-- 搜索板块 -->
          <!--          ref="formRef" :model="form" label-width="80px" inline-->
          <el-form
            ref="formRef"
            :model="queryParams"
            label-width="80px"
            inline
            class="search-form"
          >
            <el-form-item>
              <el-input
                v-model="queryParams.serviceName"
                placeholder="请输入接口名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-select v-model="queryParams.systemId" clearable placeholder="请选择系统名称">
                <el-option
                  v-for="(item, index) in systemIdList"
                  :key="index"
                  :label="item.systemCode + ' / ' + item.systemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-select v-model="queryParams.manageType" clearable placeholder="请选择服务类型">
                <el-option
                  v-for="(item, index) in dictOptions.manage_type"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item class="query-action">

              <el-dropdown trigger="click" style="margin-right: 10px;">
                <el-button class="el-dropdown-link">
                  导出<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
                  <el-dropdown-item @click.native="handleDownload('all')"> 导出所有 </el-dropdown-item>
                  <el-dropdown-item @click.native="handleDownload()"> 导出选中 </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button @click="handleImport">导入</el-button>

              <el-button
                @click="handleReset"
              >重置</el-button>
              <el-button
                v-permission="['SERVICEMONITOR_SEARCH_BUTTON']"
                type="primary"
                @click="handleQuery"
              >搜索</el-button>
              <el-button
                v-permission="['SERVICEMONITOR_ADD_BUTTON']"
                type="primary"
                @click="handleAdd"
              >新增</el-button>
              <el-button
                v-permission="['SERVICEMONITOR_DEL_BUTTON']"
                type="danger"
                :disabled="ids.length === 0"
                @click="handleDelete"
              > 删除 </el-button>
            </el-form-item>
          </el-form>
          <!-- 表格数据视图 -->
          <div>
            <DragTable
              v-loading="loading"
              :table-data="tableData"
              :drop-col="dropCol"
              :col-list="colList"
              @multipleSelectionChange="multipleSelectionChange"
              @changeType="changeType"
              @showMonitorLog="showMonitorLog"
              @handleUpdate="handleUpdate"
              @handleDelete="handleDelete"
            >
              <!--              <template #setting>-->
              <!--                <el-button type="text" icon="el-icon-sort" size="small">拖拽</el-button>-->
              <!--              </template>-->
            </DragTable>
            <el-pagination
              :page-size="pagination.pageSize"
              :current-page.sync="pagination.pageNo"
              layout="prev, pager, next, jumper"
              :total="pagination.totalPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 添加或修改接口服务监测对话框 -->
        <AddService ref="AddServiceRef" @getList="getList" />
        <!-- 详情弹框 -->
        <dt-detail ref="dtDetailRef" :dt-detail-option="detailOption" />
        <monitor-log ref="monitorLog" />

        <dtDialog
          title="导入"
          :visible.sync="fileUploadVisible"
          class="request-party-service-manage-import-dialog"
          width="620px"
          :is-loading="uploadLoading"
          @closeDialog="fileUploadVisible = false"
          @comfirmBtn="importDataSave"
        >
          <el-form slot="content">
            <div class="">
              <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="fileName" />
            </div>
          </el-form>
        </dtDialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listServiceMonitor,
  getServiceMonitor,
  delServiceMonitor,
  addServiceMonitor,
  updateServiceMonitor,
  connectTest,
  downloadTemplateApiInter,
  exportAllInter,
  partExportInter,
  uploadApiInter
} from '@/api/serviceMonitor/ServiceMonitor'
import { getSystemListApi, pageApi } from '@/api/serviceManage/requestPartyServiceManage'
import { listMonitorAlarmUser } from '@/api/contactAlarm'
import { addRes, editRes } from '@/utils/editAlarmUser'
import { changeTaskStatus } from '@/api/serviceWatch'
import Sortable from 'sortablejs'
import MonitorLog from '@/views/serviceMonitor/monitorLog.vue'
import AddService from '@/views/serviceMonitor/components/addService.vue'
import DragTable from '@/views/serviceMonitor/components/DragTable.vue'
import dictMixin from '@/utils/mixins/dict'
import dictAPI from '@/api/common'
export default {
  name: 'ServiceMonitor',
  components: {
    MonitorLog,
    AddService,
    DragTable
  },
  mixins: [
    dictMixin(['monitorStatus', 'manage_type'])
  ],
  data() {
    return {
      multipleSelection: [],
      fileName: '接口服务状态监控导入',
      handleImportTemplate: downloadTemplateApiInter,
      fileUploadVisible: false,
      uploadLoading: false,
      receiveUserList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否可提交
      canClick: false,
      // 总条数
      total: 0,
      // 接口服务监测表格数据
      tableData: [],
      systemIdList: [],
      dropCol: [
        { label: '系统名称', prop: 'systemName', width: 200 },
        { label: '服务类型', prop: 'manageTypeMy', width: 200 },
        { label: '接口服务名称', prop: 'serviceName', width: 200 },
        { label: '创建时间', prop: 'createTime', width: 200 },
        { label: '创建人', prop: 'createUserName', width: 200 },
        { label: '当前状态', prop: 'statusMy', width: 200 },
        { label: '状态更新时间', prop: 'statusUpTime', width: 200 },
        { label: '备注', prop: 'remarks', width: 200 }
      ],
      colList: [
        { label: '系统名称', prop: 'systemName', width: 200 },
        { label: '服务类型', prop: 'manageTypeMy', width: 200 },
        { label: '接口服务名称', prop: 'serviceName', width: 200 },
        { label: '创建时间', prop: 'createTime', width: 200 },
        { label: '创建人', prop: 'createUserName', width: 200 },
        { label: '当前状态', prop: 'statusMy', width: 200 },
        { label: '状态更新时间', prop: 'statusUpTime', width: 200 },
        { label: '备注', prop: 'remarks', width: 200 }
      ],
      // 查询参数
      queryParams: {
        serviceName: '',
        systemId: null,
        manageType: null
      },
      // 分页相关
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPage: 0
      },
      // 服务类型
      manageTypeList: []
    }
  },
  computed: {
    // 详情参数
    detailOption() {
      return {
        rows: [
          {
            label: '系统id',
            prop: 'systemId'
          },
          {
            type: 'dict',
            options: this.dictOptions.manage_type,
            label: '服务管理分类  1-请求方服务  2-提供方服务',
            prop: 'manageType'

          },
          {
            label: '服务id',
            prop: 'serviceId'

          },
          {
            label: '请求参数',
            prop: 'params'

          },
          {
            label: 'cron表达式',
            prop: 'cron'

          },
          {
            label: '备注',
            prop: 'remarks'

          },
          {
            label: '当前状态',
            prop: 'status'

          },
          {
            label: '状态更新时间',
            prop: 'statusUpTime'

          }
        ],
        data: {}
      }
    }
  },
  created() {
    this.infoData()
    listMonitorAlarmUser({ pageNo: 1, pageSize: -1 }).then(res => {
      this.receiveUserList = res.data.rows
    })
    dictAPI.mulFetchPage(['manage_type']).then(res => {
      this.manageTypeList = res.data.manage_type
      this.getList()
    })
  },
  mounted() {
    this.columnDrop()
  },
  methods: {
    // 选中行
    multipleSelectionChange(val) {
      this.ids = []
      this.multipleSelection = val
      this.ids = val.map(item => {
        return item.id
      })
    },
    // 上传文件
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      uploadApiInter(formData).then(async(res) => {
        this.uploadLoading = true
        this.fileUploadVisible = false
        if (res.errorDownloadPath) {
          this.$alert('<div> <div class="title">' + res.tip + '</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败用户信息</span> </div> </div>', '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert('<div> <div class="title">' + res.tip + '导入完成', {
            dangerouslyUseHTMLString: true
          })
        }
        this.getList()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function() {
          window.location.href = res.errorDownloadPath
        }
        this.uploadLoading = false
      }).catch(res => {
        this.uploadLoading = false
      })
    },

    async handleImport() {
      this.fileUploadVisible = true
      await this.$nextTick()
      this.$refs.dtImportFileRef.fileList = []
    },

    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        this.showScreenLoading()
        exportAllInter().then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '接口服务状态监控全部导出' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map(res => {
          return res.id
        })
        con = {
          serviceMonitorIds: ids.join(',')
        }
        this.showScreenLoading()
        partExportInter(con).then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '接口服务状态监控部分导出' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      }
    },

    /** 列拖拽 */
    columnDrop() {
      const tHeader = document.querySelector('.el-table__header-wrapper tr')
      this.sortable = Sortable.create(tHeader, {
        animation: 180,
        /** 延迟 */
        // delay: 1,
        filter: '.disabled',
        onEnd: (evt) => {
          const oldItem = this.dropCol[evt.oldIndex]
          this.dropCol.splice(evt.oldIndex, 1)
          this.dropCol.splice(evt.newIndex, 0, oldItem)
        }
      })
    },
    changeType(val) {
      this.loading = true
      const data = {
        ids: [val.id],
        type: '3',
        taskStatus: val.taskStatus === '1' ? '2' : '1'
      }
      changeTaskStatus(data).then(res => {
        if (res.code === '00000') {
          this.$message.success(data.taskStatus === '1' ? '启用成功' : '停用成功')
          this.getList()
        }
      })
    },
    /** 查询接口服务监测列表 */
    getList() {
      this.loading = true
      listServiceMonitor({
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        ...this.queryParams
      }).then(({ data: response }) => {
        this.tableData = response.rows.map(item => {
          const obj = this.manageTypeList.find(ele => ele.dictCode === item.manageType)
          const manageTypeMy = obj ? obj.dictName : ''
          const statusMy = item.status == '1' ? '正常' : '异常'
          return {
            ...item,
            manageTypeMy,
            statusMy
          }
        })
        this.total = response.totalRows
      }).finally(e => {
        this.loading = false
      })
    },
    infoData() {
      this.getSystemListApi()
    },
    // 取消按钮
    cancel() {
      this.reset()
    },
    getSystemListApi() {
      getSystemListApi()
        .then(({ code, data }) => {
          if (code === '00000') {
            this.systemIdList = data
          }
        })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        systemId: null,
        manageType: null,
        serviceId: null,
        params: null,
        cron: null,
        remarks: null,
        status: '0',
        statusUpTime: null,
        delFlag: null,
        createTime: null,
        createUser: null,
        updateTime: null,
        updateUser: null
      }
      this.open = false
      this.canClick = false
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        serviceName: '',
        systemId: null,
        manageType: null
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.$refs.AddServiceRef.open = true
      this.$refs.AddServiceRef.title = '添加接口服务监测'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getServiceMonitor(id).then(response => {
        this.$refs.AddServiceRef.open = true
        pageApi({
          systemId: response.data.systemId,
          manageType: response.data.manageType,
          pageNo: 1,
          pageSize: -1
        }).then(({ data: res }) => {
          this.$refs.AddServiceRef.serviceManagerList = res.rows
          this.$refs.AddServiceRef.interfaceData(data.serviceId)
        })
        const data = response.data
        data.alarmUsers = editRes(response.data.alarmUsers)
        this.$refs.AddServiceRef.form = data
        this.$refs.AddServiceRef.domains = data.monitorParamList
        this.$refs.AddServiceRef.title = '修改接口服务监测'
      })
    },
    handleDetail(row) {
      this.detailOption.data = row
      this.$refs.dtDetailRef.dialogVisible = true
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        const data = JSON.parse(JSON.stringify(this.form))
        data.alarmUsers = addRes(data.alarmUsers)
        if (valid) {
          if (this.form.id != null) {
            updateServiceMonitor(data).then(response => {
              this.$dtModal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addServiceMonitor(data).then(response => {
              this.$dtModal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 测试连接按钮 */
    testConnect() {
      const data = JSON.parse(JSON.stringify(this.form))
      data.alarmUsers = addRes(data.alarmUsers)
      this.$refs['form'].validate(valid => {
        if (valid) {
          connectTest(data).then(response => {
            if (response.data) {
              this.$dtModal.msgSuccess('连接成功')
              this.canClick = true
            } else {
              this.$dtModal.msgError('连接失败')
            }
          })
        }
      })
    },
    showMonitorLog(row) {
      this.$refs.monitorLog.init(row.id, 3, row.serviceName, row.interfaceAddress)
    },
    addCron() {
      this.$refs.vcrontabRef.showDialog()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$dtModal.confirm('是否确认删除接口服务监测数据项？').then(function() {
        return delServiceMonitor(ids)
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      })
    },
    // 分页操作
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.pagination.pageNo = val
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.request-party-service-manage {
  background: #F2F2F2;

  &-body {
    background: #fff;
    margin-top: 10px;
    padding: 20px;
    height: calc(100vh - 254px);
    overflow-y: auto;
  }
  .el-pagination {
    text-align: right;
    margin-top: 20px;
  }

  .el-tree {
    ::v-deep .el-tree-node__expand-icon {
      font-size: 18px;
    }
    .custom-tree-node {
      width: calc(100% - 30px);
      display: flex;
      align-items: center;
      padding-right: 20px;

      > span:first-child {
        display: inline-block;
        width: calc(100% - 50px);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: 40px;
      }

      .tree-btn {
        .el-switch {
          margin-top: -4px;
          margin-left: 10px;
        }
      }
    }
  }
}
::v-deep.request-party-service-manage-import-dialog {
  .el-upload-list__item {
    transition: none !important;
  }
  .el-upload-list__item-name {
    transition: none !important;
  }
}
</style>
